package com.andy.nature.ui.activity

import com.andy.base.utils.MVUtils
import com.andy.common.base.BaseVMActivity
import com.andy.common.extend.setOnIMClickListener
import com.andy.nature.databinding.ActivityLoginBinding
import com.andy.nature.vm.LoginViewModel
import com.andy.toast.extend.showErrorToast

/**
 * Author:Andy
 * Date:2023/4/27 17:51
 * Description:LoginActivity
 */
class LoginActivity : BaseVMActivity<ActivityLoginBinding, LoginViewModel>() {
    private var telephone: String? = null
    private var password: String? = null

    companion object {
        const val KEY_TEL = "telephone"
        const val KEY_PASSWORD = "password"
    }

    override fun viewModelClass(): Class<LoginViewModel> {
        return LoginViewModel::class.java
    }

    override fun getViewBinding(): ActivityLoginBinding {
        return ActivityLoginBinding.inflate(layoutInflater)
    }

    override fun initObserve() {
        mViewModel.loginData.observe(this) {
            if (it.code == "100" || it.message == "登录成功") {
                MVUtils.put(KEY_TEL, telephone)
                MVUtils.put(KEY_PASSWORD, password)
                startActivity(RecruitActivity::class.java)
                finish()
            } else {
                it.message.showErrorToast()
            }
        }
    }

    override fun initData() {
        mBinding?.apply {
            telephone = MVUtils.getString(KEY_TEL, "")
            password = MVUtils.getString(KEY_PASSWORD, "")
            if (!telephone.isNullOrEmpty()) {
                edtPhone.setText(telephone)
            }
            if (!password.isNullOrEmpty()) {
                edtPassword.setText(password)
            }
        }
    }

    override fun initAction() {
        mBinding?.apply {
            btnLogin.setOnIMClickListener {
                telephone = edtPhone.text.toString().trim()
                password = edtPassword.text.toString().trim()
                if (telephone.isNullOrEmpty()) {
                    "请输入手机号".showErrorToast()
                    return@setOnIMClickListener
                }
                if (password.isNullOrEmpty()) {
                    "请输入密码".showErrorToast()
                    return@setOnIMClickListener
                }
                mViewModel.login(telephone!!, password!!)
            }
        }
    }

}